package org.west.sky.frame.activiti.study.chapter8;

import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Job;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.west.sky.frame.activiti.study.util.ActivitiEngineUtil;

import java.util.List;

/**
 * author: chz
 * date: 2024/9/6
 * description: 任务执行
 */
public class RunDemo8_11 extends ActivitiEngineUtil {

    public static void main(String[] args) {
        RunDemo8_11 runDemo8_3 = new RunDemo8_11();
        runDemo8_3.runDemo();
    }

    private void runDemo() {
        loadActivitiConfigAndInitEngine("activiti.cfg.xml");

        ProcessDefinition processDefinition = deployByClassPathResource("processes/chapter8/Chapter8_4.bpmn20.xml");
        System.out.println("流程定义ID:" + processDefinition.getId() + ",流程定义名称:" + processDefinition.getName());

        //发起流程
        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId());
        System.out.println("发起流程实例成功，流程实例id:" + processInstance.getId());
        //查询第一个任务
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        System.out.println("第一个任务id:" + task.getId() + "，任务名称:" + task.getName());
        //完成任务
        taskService.complete(task.getId());
        //查询job任务列表
        List<Job> jobs = managementService.createTimerJobQuery().processInstanceId(processInstance.getId()).list();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        for (Job job : jobs) {
            System.out.println("job任务id:" + job.getId() + ",job任务类型:" + job.getJobType() + "，执行时间：" + sdf.format(job.getDuedate()));
            managementService.moveTimerToExecutableJob(job.getId());
            System.out.println("立即执行任务：" + job.getId());
            managementService.executeJob(job.getId());
        }

        HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstance.getId()).singleResult();
        System.out.println("流程实例开始时间：" + sdf.format(historicProcessInstance.getStartTime())
                + ",流程实例结束时间：" + sdf.format(historicProcessInstance.getEndTime()));
        processEngine.close();
    }

}
